package org.example;/*
 * title:
 * author:
 * date:
 * description:
 * */
class Task implements Runnable {
    private String name;

    public Task(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println("Task " + name + " started by " + Thread.currentThread().getName());
        // 模拟执行任务
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Task " + name + " finished by " + Thread.currentThread().getName());
    }
}
public class MultiThreadExample {
    public static void main(String[] args) {
        System.out.println("Main thread starts.");

        // 创建并启动5个子线程
        for (int i = 1; i <= 5; i++) {
            int taskId = i;
            new Thread(() -> {
                System.out.println("Sub-thread " + Thread.currentThread().getName() + " starts.");

                // 在每个子线程中创建并启动一个孙线程
                Thread grandChildThread = new Thread(new Task("Task " + taskId), "GrandChildThread-" + taskId);
                grandChildThread.start();

                try {
                    // 等待孙线程执行完毕
                    grandChildThread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("Sub-thread " + Thread.currentThread().getName() + " ends.");
            }, "SubThread-" + i).start();
        }

        // 主线程等待所有子线程结束（这里为了简化示例，未实现等待逻辑）
        // 实际应用中可能需要更复杂的同步机制来确保所有子线程执行完毕
        System.out.println("Main thread ends.");
    }
}


